package com.ccit.sand.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.easysdk.factory.Factory;
import com.ccit.common.result.Result;
import com.ccit.model.Order;
import com.ccit.sand.common.AliReturnPay;
import com.ccit.sand.config.AlipayConfig;
import com.ccit.sand.service.PayCommonService;
import com.ccit.sand.util.ParamsUtil;
import com.ccit.sand.util.WebSocket;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/sandbox")
public class PayController {


    @Resource
    private AlipayConfig aliPayConfig;
    @Autowired
    private WebSocket webSocket;

    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "utf-8";
    private static final String SIGN_TYPE = "RSA2";

    @GetMapping("/sandboxPay")
    public void pay(@RequestParam String type,
                    @RequestParam String price,
                    @RequestParam String subject, HttpServletResponse httpResponse) throws Exception {
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        request.setBizContent("{\"out_trade_no\":\"" + type + UUID.randomUUID().toString().replaceAll("-", "") + "\","
                + "\"total_amount\":\"" + price + "\","
                + "\"subject\":\"" +subject + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            // 调用SDK生成表单
            form = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        // 直接将完整的表单html输出到页面
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

//    public Result sandboxPay(@RequestBody @Valid AliReturnPay aliReturnPay) throws IOException, AlipayApiException {
//
//
//    }
//在这里写一段向支付宝发送订单信息的接口
//    public Result sandboxPay(@RequestBody @Valid AliReturnPay aliReturnPay) throws IOException, AlipayApiException {
//        try {
//            CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
//            certAlipayRequest.setServerUrl(GATEWAY_URL);
//            certAlipayRequest.setAppId(alipayConfig.getAppId());
//            certAlipayRequest.setPrivateKey(alipayConfig.getAppPrivateKey());
//            certAlipayRequest.setFormat(FORMAT);
//            certAlipayRequest.setCharset(CHARSET);
//            certAlipayRequest.setSignType(SIGN_TYPE);
//            certAlipayRequest.setCertPath(alipayConfig.getCertPath());
//        }
//    }

    @PostMapping("/callback")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                // System.out.println(name + " = " + request.getParameter(name));
            }

            String tradeNo = params.get("out_trade_no");
//            String gmtPayment = params.get("gmt_payment");
//            String alipayTradeNo = params.get("trade_no");
            // 支付宝验签
            if (Factory.Payment.Common().verifyNotify(params)) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
                if ("TRADE_SUCCESS".equals(params.get("trade_status"))) {
                    // 处理支付成功的逻辑
                    webSocket.sendMessage("true");
                }
            }
        }
        return "success";
    }

//    @PostMapping("/precreate")
//    public Result precreate(@RequestBody @Valid PayRequest request) {
//        try {
//            AlipayTradePrecreateRequest req = new AlipayTradePrecreateRequest();
//            req.setNotifyUrl(notifyUrl);
//
//            JSONObject bizContent = new JSONObject();
//            bizContent.put("out_trade_no", generateOrderNo(request.getType()));
//            bizContent.put("total_amount", formatAmount(request.getPrice()));
//            bizContent.put("subject", request.getSubject());
//            bizContent.put("timeout_express", "60m");
//
//            req.setBizContent(bizContent.toJSONString());
//
//            AlipayTradePrecreateResponse response = alipayClient.execute(req);
//            return Result.ok(response.getQrCode());
//        } catch (AlipayApiException e) {
//            return handleAlipayException(e);
//        }
//    }
//
//    private String formatAmount(Double price) {
//        return String.format("%.2f", price); // 强制两位小数
//    }
//
//    private String generateOrderNo(String type) {
//        return type + UUID.randomUUID().toString().replace("-", "");
//    }
//
//    private Result handleAlipayException(AlipayApiException e) {
//        if (e.getCause() instanceof SocketTimeoutException) {
//            return Result.fail("ALIPAY_TIMEOUT", "支付宝接口响应超时，请稍后重试");
//        }
//        return Result.fail("ALIPAY_ERROR", e.getErrMsg());
//    }
}
